<template>
  <slot></slot>
</template>
<script setup>
const emits = defineEmits(['change']);
</script>
<script>
import {isEmpty, isNotEmpty} from '@/utils/CommonUtils';

export default {
  name: 'FGroupCheck',
  provide() {
    return {
      groupCheckSelection: this.groupCheckSelection
    };
  },
  props: {
    value: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      groupCheckSelection: {
        selectedKeys: [],
        isSelectAll: false,
        checkBoxKeySet: new Set(),
        onChange: this.onSelectionChange
      },
    };
  },
  methods: {
    resolveSelectAll() {
      if (isEmpty(this.groupCheckSelection.selectedKeys)) {
        this.groupCheckSelection.isSelectAll = false;
        return;
      }
      let checkBoxKeyList = [...this.groupCheckSelection.checkBoxKeySet];
      if (this.groupCheckSelection.selectedKeys.length === checkBoxKeyList.length) {
        this.groupCheckSelection.isSelectAll = true;
        return;
      }
      this.groupCheckSelection.isSelectAll = false;
    },
    onSelectionChange() {
      this.resolveSelectAll();
      let list = this.groupCheckSelection.selectedKeys;
      this.value.splice(0, this.value.length);
      this.value.splice(0, 0, ...list);
      this.$emit('change')
    },
  },
  watch: {
    value: {
      handler(newValue, oldValue) {
        if (newValue === oldValue) return;
        let list = [];
        if (isNotEmpty(newValue)) list = newValue;
        this.groupCheckSelection.selectedKeys = list;
        this.resolveSelectAll();
        this.$emit('change')
      },
      deep: true,
    },
  }
};
</script>
